package main

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/driver/desktop"
	"fyne.io/fyne/v2/widget"
	"fyne_tomato/pkg"
	"image/color"
	"runtime"
	"time"
)

const (
	workTime  = 25 * 60
	breakTime = 5 * 60
	longBreak = 15 * 60
)

type Tomato struct {
	app          fyne.App
	window       fyne.Window
	duration     int
	timerLabel   *canvas.Text
	btn          *widget.Button
	isRunning    bool
	sessionNum   int
	sessionLabel *canvas.Text
}

func NewTomato() *Tomato {
	tomato := &Tomato{
		app:        app.New(),
		duration:   workTime,
		isRunning:  false,
		sessionNum: 1,
	}
	tomato.MakeUI()
	return tomato
}

func (t *Tomato) MakeUI() {
	//t.app.Settings().SetTheme(&theme.MyTheme{})

	// 系统托盘
	if desk, ok := t.app.(desktop.App); ok {
		m := fyne.NewMenu("Tomato",
			fyne.NewMenuItem("显示窗口", func() {
				t.window.Show()
			}))
		desk.SetSystemTrayMenu(m)
	}

	t.window = t.app.NewWindow("番茄时钟")
	t.window.Resize(fyne.NewSize(255, 0))
	t.window.SetMaster()
	t.window.SetCloseIntercept(func() {
		t.window.Hide()
	})

	t.btn = widget.NewButton("Start", func() {
		if t.isRunning {
			t.pause()
		} else {
			t.start()
		}
	})

	t.timerLabel = canvas.NewText(pkg.ResolveTime(t.duration), color.Black)
	t.timerLabel.Alignment = fyne.TextAlignCenter
	t.timerLabel.TextSize = 64
	t.sessionLabel = canvas.NewText("Work Time", color.Black)
	t.sessionLabel.Alignment = fyne.TextAlignCenter
	t.sessionLabel.TextSize = 16
	t.window.SetContent(container.NewVBox(t.sessionLabel, t.timerLabel, t.btn))
}

func (t *Tomato) updateTime() {
	//for t.isRunning && t.duration >= 0 {
	//	t.timerLabel.SetText(t.duration.String())
	//	if t.duration == 0 {
	//		t.finishSession()
	//		runtime.Goexit()
	//	}
	//	time.Sleep(time.Second)
	//	t.duration -= time.Second
	//}

	for range time.Tick(time.Second) {
		if !t.isRunning {
			runtime.Goexit()
		} else if t.duration == 0 {
			t.finishSession()
			runtime.Goexit()
		} else {
			t.duration -= 1
			t.timerLabel.Text = pkg.ResolveTime(t.duration)
			t.timerLabel.Refresh()
		}
	}
}

func (t *Tomato) start() {
	t.btn.SetText("Pause")
	t.isRunning = true

	go t.updateTime()
}

func (t *Tomato) pause() {
	t.btn.SetText("Start")
	t.isRunning = false
}

func (t *Tomato) finishSession() {
	t.pause()

	content := "休息一下吧！"
	t.sessionNum++
	if t.sessionNum == 8 {
		t.sessionLabel.Text = "Long Break Time"
		content = "这次好好休息一下吧！"
		t.duration = longBreak
		t.sessionNum = 0
	} else if t.sessionNum%2 == 0 {
		t.sessionLabel.Text = "Break Time"
		t.duration = breakTime
	} else {
		t.sessionLabel.Text = "Work Time"
		content = "开始工作吧！"
		t.duration = workTime
	}

	t.timerLabel.Text = pkg.ResolveTime(t.duration)
	t.timerLabel.Refresh()
	t.sessionLabel.Refresh()

	notification := fyne.NewNotification("温馨提示：", content)
	t.app.SendNotification(notification)
}

func main() {
	tomato := NewTomato()
	tomato.window.ShowAndRun()
}
